package com.beiye.drivertransport.fragment;


import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.adapter.LearnPagerAdapter;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.NewstypesBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.MessageEventOrgid;
import com.beiye.drivertransport.utils.UserManger;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


import okhttp3.Call;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
//信息界面
public class NoticeFragment extends HomeFgt {
    //    @Bind(R.id.listview_message1)
//    LRecyclerView listviewMessage;
//    @Bind(R.id.empty_view)
//    View empty_view;
//    ArrayList<LoginUserBean.DataBean.CurUserOrgBean> cusList = new ArrayList<>();
//    private PopWindowApt popWindowApt;
//    private PopupWindow mPopWindow;
//    private MessageNoticeApt messagenoticeApt;
//    private LRecyclerViewAdapter lRecyclerViewAdapter;
//    private String creatime;
//    private int firstIndex=1;
//    private int pageSize=15;

    RelativeLayout rlMsgCountFrame;//红点

    TabLayout TabLayout1;
    private int TAB_MARGIN_DIP = 10;

    ViewPager myviewpager;

    //    private LearnPagerAdapter adapter;
    private ArrayList<NewstypesBean.RowsBean> newsstypelist = new ArrayList<>();
    private LearnPagerAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_notice;
    }



    @Override
    public void initData() {

        TabLayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                if (null == view) {
                    tab.setCustomView(R.layout.custom_tab_layout_text);
                }
                TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                if (textView.getText().toString().trim().equals("通知")) {
                    textView.setTextColor(getActivity().getResources().getColor(R.color.newgreen));
                } else {
                    textView.setTextColor(getActivity().getResources().getColor(R.color.white_name));
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

                View view = tab.getCustomView();
                if (null == view) {
                    tab.setCustomView(R.layout.custom_tab_layout_text);
                }
                TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
                textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                if (textView.getText().toString().trim().equals("通知")) {
                    textView.setTextColor(getActivity().getResources().getColor(R.color.newgreen));
                } else {
                    textView.setTextColor(getActivity().getResources().getColor(R.color.white_name));
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {


            }
        });
    }

    private void initTablayout() {
        /*ArrayList<Fragment> fragments = new ArrayList<Fragment>();
        MechanismNoticeFragment mechanismNoticeFragment = new MechanismNoticeFragment();
        fragments.add(mechanismNoticeFragment);
        ArrayList<String> list_title = new ArrayList<>();
        list_title.add("通知");
        TabLayout1.addTab(TabLayout1.newTab().setText(list_title.get(0)));
        for (int i = 0; i < newsstypelist.size(); i++) {
            JournalismFragment journalismFragment = new JournalismFragment();
            fragments.add(journalismFragment);
            Bundle args = new Bundle();
            args.putInt("ntId", newsstypelist.get(i).getNtId());
            journalismFragment.setArguments(args);
            list_title.add(newsstypelist.get(i).getNtName());
            TabLayout1.addTab(TabLayout1.newTab().setText(list_title.get(i + 1)));
        }
        //       TabLayout1.getTabAt(0).select();

        //   将名称加载tab名字列表，正常情况下，我们应该在values/arrays.xml中进行定义然后调用
        adapter = new LearnPagerAdapter(getChildFragmentManager(), fragments, list_title);
        myviewpager.setOffscreenPageLimit(1);
        myviewpager.setAdapter(adapter);
        TabLayout1.setupWithViewPager(myviewpager);
        setIndicator(getActivity(), TabLayout1, TAB_MARGIN_DIP, TAB_MARGIN_DIP);*/
    }


//    private List<FragmentInfo>  initFragments(){
//
//        List<FragmentInfo> mFragments = new ArrayList<>(newsstypelist.size()+1);
//            mFragments.add(new FragmentInfo("通知",MechanismNoticeFragment.class));
//           for (int i = 0; i < newsstypelist.size(); i++) {
//      //         JournalismFragment journalismFragment = new JournalismFragment();
//               mFragments.add(new FragmentInfo(newsstypelist.get(i).getNtName(), JournalismFragment.class));
////               Bundle args = new Bundle();
////               args.putInt("ntId", newsstypelist.get(i).getNtId());
////               journalismFragment.setArguments(args);
//           }
//
//        return  mFragments;
//    }
//    private void initTablayout() {
//        PagerAdapter adapter = new
//                NewsViewPagerAdapter(getChildFragmentManager(),initFragments());
//        myviewpager.setOffscreenPageLimit(adapter.getCount());
//        myviewpager.setAdapter(adapter);
//
//        // Tablayout 关联 viewPager
//        TabLayout1.setupWithViewPager(myviewpager);
//        TabLayout1.getTabAt(0).select();
//        setIndicator(getActivity(), TabLayout1, TAB_MARGIN_DIP, TAB_MARGIN_DIP);
//        TabLayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//            @Override
//            public void onTabSelected(TabLayout.Tab tab) {
//                View view = tab.getCustomView();
//                if (null == view) {
//                    tab.setCustomView(R.layout.custom_tab_layout_text);
//                }
//                TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
//                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
//                textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
//                if (textView.getText().toString().trim().equals("通知")) {
//                    textView.setTextColor(getActivity().getResources().getColor(R.color.newgreen));
//                }else{
//                    textView.setTextColor(getActivity().getResources().getColor(R.color.white_name));
//                }
//
//            }
//
//            @Override
//            public void onTabUnselected(TabLayout.Tab tab) {
//
//                View view = tab.getCustomView();
//                if (null == view) {
//                    tab.setCustomView(R.layout.custom_tab_layout_text);
//                }
//                TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
//                textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
//                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
//                if (textView.getText().toString().trim().equals("通知")) {
//                    textView.setTextColor(getActivity().getResources().getColor(R.color.newgreen));
//                }else{
//                    textView.setTextColor(getActivity().getResources().getColor(R.color.white_name));
//                }
//            }
//
//            @Override
//            public void onTabReselected(TabLayout.Tab tab) {
//
//
//            }
//        });
//    }

    //修改tablayout的tabIndicator宽度
    public void setIndicator(Context context, TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field slidingTabIndicatorField = null;
        try {
            slidingTabIndicatorField = tabLayout.getDeclaredField("slidingTabIndicator");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        slidingTabIndicatorField.setAccessible(true);
        LinearLayout ll_tab = null;
        try {
            ll_tab = (LinearLayout) slidingTabIndicatorField.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) (getDisplayMetrics(context).density * leftDip);
        int right = (int) (getDisplayMetrics(context).density * rightDip);

        for (int i = 0; i < ll_tab.getChildCount(); i++) {
            View child = ll_tab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    public DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric;
    }

    public float getPXfromDP(float value, Context context) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value,
                context.getResources().getDisplayMetrics());
    }


    @Override
    public void requestData() {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        //通知红点
        OkGo.get(AppInterfaceConfig.BASE_URL + "sys/notice/getUnViewStatus/" + userId)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {

                        CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
                        Integer data1 = checkBean.getData();
                        if (data1 >= 1) {

                            rlMsgCountFrame.setVisibility(View.VISIBLE);
                        } else if (data1 == 0) {
                            rlMsgCountFrame.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }
                });
        showLoadingDialog("");
        //查询新闻种类
        new Login().getNewstypes(1, this, 1);
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            dismissLoadingDialog();
            NewstypesBean newstypesBean = JSON.parseObject(result, NewstypesBean.class);
            List<NewstypesBean.RowsBean> rows = newstypesBean.getRows();
            newsstypelist.clear();

            newsstypelist.addAll(rows);
            initTablayout();
        }
        super.onSuccess(result, call, response, what);
    }

    @Override
    public void onResume() {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        //通知红点
        OkGo.get(AppInterfaceConfig.BASE_URL + "sys/notice/getUnViewStatus/" + userId)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {

                        CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
                        Integer data1 = checkBean.getData();
                        if (data1 >= 1) {

                            rlMsgCountFrame.setVisibility(View.VISIBLE);
                        } else if (data1 == 0) {
                            rlMsgCountFrame.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }
                });


        EventBus.getDefault().post(new MessageEventOrgid(1));//刷新通知企业对应最新数据
        super.onResume();
    }

//    @Override
//    public void onSuccess(String result, Call call, Response response, int what) {
//        if(what==1)
//        {
//            HomeNewsListViewBean homeNewsListViewBean = JSON.parseObject(result, HomeNewsListViewBean.class);
//            List<HomeNewsListViewBean.RowsBean> rowsBeanList = homeNewsListViewBean.getRows();
//            if(rowsBeanList.size()==0)
//            {
//                return;
//            }else if(rowsBeanList.size()>0)
//            {
//                int viewMark = rowsBeanList.get(0).getViewMark();
//                if(viewMark==1)
//                {
//                    return;
//                }else {
//                    showNotification(rowsBeanList);
//                }
//            }
//
//        }
//
//
//        super.onSuccess(result, call, response, what);
//    }

//    private void showNotification(List<HomeNewsListViewBean.RowsBean> rowsBeanList) {
//        String noticeTitle =rowsBeanList.get(0).getNoticeTitle();
//        int noticeSn=rowsBeanList.get(0).getNoticeSn();
//        long creationDate =rowsBeanList.get(0).getCreationDate();
//        Date date = new Date(creationDate);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//         String     creatime = sdf.format(date);
//        Bitmap btm= BitmapFactory.decodeResource(getResources(), R.drawable.logo_share);
//        NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(getActivity()).setSmallIcon(R.mipmap.logo)
//        .setContentTitle(noticeTitle);
//        mBuilder.setTicker("新的消息");
//        mBuilder.setLargeIcon(btm);
//        mBuilder.setAutoCancel(true);
//        mBuilder.setPriority(Notification.PRIORITY_MAX);
//        mBuilder.setDefaults(Notification.DEFAULT_ALL);
//        mBuilder.setOnlyAlertOnce(true);
//        //构建一个intent
//        Intent resultIntent=new Intent(getActivity(), NoticeItemActivity.class);
//        int sn =rowsBeanList.get(0).getSn();
//        OkGo.get(AppInterfaceConfig.BASE_URL+"sys/noticeUser/"+sn)
//                .tag(this)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String result, Call call, Response response) {
//                        resultIntent.putExtra("pic_url",noticeSn);
//                        resultIntent.putExtra("creatime",creatime);
//                        PendingIntent resultPI=PendingIntent.getActivity(getActivity(),0,resultIntent,PendingIntent.FLAG_CANCEL_CURRENT);
//                        mBuilder.setContentIntent(resultPI);
//                        NotificationManager mNotif= (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
//                        mNotif.notify(2,mBuilder.build());
//
//                    }
//
//                    @Override
//                    public void onError(Call call, Response response, Exception e) {
//                        super.onError(call, response, e);
//
//                    }
//                });
//
//
//
//
//    }

    @Override
    public void onUserVisible() {

    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;
    }

}
